package org.dizena.gateway.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;


@Component
@Slf4j
public class TokenGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenGatewayFilterFactory.Config> {


    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("enabled");
    }

    public TokenGatewayFilterFactory() {
        super(Config.class);
        log.info("Loaded TokenGatewayFilterFactory");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            if (!config.isEnabled()) {
                return chain.filter(exchange);
            }

            if (null != exchange) {
                ServerHttpRequest httpRequest = exchange.getRequest();
                try {
                    HttpHeaders headers = httpRequest.getHeaders();
                    log.info("headers {}", headers);
                    String reqId = headers.getFirst(ConstantHeaderKey.ACCESS_ID);
                    String reqTime = headers.getFirst(ConstantHeaderKey.ACCESS_TIME);
                    log.info("{} {}", reqId, reqTime);
                    if (reqId == null && reqTime == null) {
                        ServerHttpRequest newHttpRequest = FilterRequestResponseUtil
                                .getNewHttpRequest(httpRequest, FilterRequestResponseUtil.getNewHttpHeadersConsumer());
                        return chain.filter(exchange.mutate().request(newHttpRequest).build());
                    }

                    return chain.filter(exchange.mutate().request(httpRequest).build());
                } catch (Exception e) {
                    return chain.filter(exchange);
                }
            }
            return chain.filter(null);
        };
    }


    public static class Config {
        /**
         * 控制是否开启
         */
        private boolean enabled;

        public Config() {
        }

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }
}

